package com.tf_cut.admin.sys.sysuser.service;

import com.tf_cut.admin.common.pojo.PageInfo;
import com.tf_cut.admin.common.pojo.Result;
import com.tf_cut.admin.common.service.CommonServiceImpl;
import com.tf_cut.admin.sys.sysauthority.service.SysAuthorityService;
import com.tf_cut.admin.sys.sysauthority.vo.SysAuthorityVo;
import com.tf_cut.admin.sys.syssetting.service.SysSettingService;
import com.tf_cut.admin.sys.sysuser.pojo.SysUser;
import com.tf_cut.admin.sys.sysuser.repository.SysUserRepository;
import com.tf_cut.admin.sys.sysuser.vo.SysUserVo;
import com.tf_cut.admin.sys.sysuserauthority.service.SysUserAuthorityService;
import com.tf_cut.admin.sys.sysuserauthority.vo.SysUserAuthorityVo;
import com.tf_cut.admin.util.CopyUtil;
import com.tf_cut.admin.util.MD5Util;
import com.tf_cut.admin.util.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SysUserServiceImpl extends CommonServiceImpl<SysUserVo, SysUser, String> implements SysUserService {

    @PersistenceContext
    private EntityManager em;
    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysSettingService sysSettingService;

    @Autowired
    private SysAuthorityService sysAuthorityService;

    @Autowired
    private SysUserAuthorityService sysUserAuthorityService;

    @Override
    public Result<PageInfo<SysUserVo>> page(SysUserVo entityVo) {
        Result<PageInfo<SysUserVo>> result = super.page(entityVo);
        //置空密码
        result.getData().getRows().forEach((sysUserVo) -> {
            sysUserVo.setPassword(null);
        });
        return result;
    }

    @Override
    public Result<SysUserVo> save(SysUserVo entityVo) {
        //新增用户，需要设置初始密码
        if (StringUtils.isEmpty(entityVo.getUserId())&& StringUtils.isBlank(entityVo.getPassword())) {
            entityVo.setPassword(MD5Util.getMD5(sysSettingService.get("1").getData().getUserInitPassword()));
        }
        return super.save(entityVo);
    }

    /**
     * 重置初始密码
     */
    @Override
    public Result<SysUserVo> resetPassword(String userId) {
        SysUserVo entityVo = new SysUserVo();
        entityVo.setUserId(userId);
        System.out.println(sysSettingService.get("1").getData().getUserInitPassword()+"==========");
        entityVo.setPassword(MD5Util.getMD5(sysSettingService.get("1").getData().getUserInitPassword()).toLowerCase());
        Result<SysUserVo> result = super.save(entityVo);
        result.getData().setPassword(null);
        return result;
    }

    /**
     * 新增用户统一入口
     * @param userName
     * @param loginName
     * @param platform
     * @return
     */
    @Override
    public Result<SysUserVo> initUser(String userName, String loginName, String platform) {
        SysUser sysUser = sysUserRepository.findByLoginName(loginName);
        if(sysUser == null) {
            SysUserVo sysUserVo = SysUserVo.builder()
                    .userId(UUIDUtil.getUUID())
                    .userName(userName)
                    .loginName(loginName)
                    .password(MD5Util.getMD5Lower("xyd123456").toLowerCase())
                    .valid("Y")                        // 是否允许登录系统
                    .limitMultiLogin("Y")            // 是否允许多人在线
                    .createTime(new Date(System.currentTimeMillis()))
                    .updateTime(new Date(System.currentTimeMillis()))
                    .lastChangePwdTime(new Date(System.currentTimeMillis()))
                    .build();
            List<SysAuthorityVo> sysAuthority = sysAuthorityService.list(SysAuthorityVo.builder().authorityName(platform).build()).getData();

            SysUserAuthorityVo build = SysUserAuthorityVo.builder().userId(sysUserVo.getUserId())
                    .authorityId(sysAuthority.get(0).getAuthorityId()).createTime(new Date()).build();

            this.sysUserAuthorityService.save(build);
            return super.save(sysUserVo);
        }else {
            return Result.of(CopyUtil.copy(sysUser, SysUserVo.class));
        }
    }

    @Override
    public Result<SysUserVo> findByLoginName(String username) {
        return Result.of(CopyUtil.copy(sysUserRepository.findByLoginName(username), SysUserVo.class));
    }

    public static void main(String[] args) {
        String aa="555070227FF7F2E2AC716F883AE98ABF";
        System.out.println(aa.toLowerCase());
    }

	@Override
	public SysUser queryAppKey(String loginId) {
		return sysUserRepository.queryAppKey(loginId);
	}
	
    @Override
    public Integer queryByLoginName(String username) {
        return sysUserRepository.queryByLoginName(username);
    }

	@Override
	public SysUser queryByMobile(String mobile) {
		return sysUserRepository.queryByMobile(mobile);
	}

	@Override
	public String findByPersonId(String mobile) {
		return sysUserRepository.findByPersonId(mobile);
	}

	@Override
	public int findByMobile(String sellerMobile) {
		return sysUserRepository.findByMobile(sellerMobile);
	}
}
